package com.fg.pro.trade.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fg.pro.model.exception.CustomException;
import com.fg.pro.model.utils.PoiUtils;
import com.fg.pro.trade.dao.TradeSaleDao;
import com.fg.pro.trade.entity.TradeSale;
import com.fg.pro.trade.entity.TradeSaleOther;
import com.fg.pro.trade.service.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.fg.pro.model.enums.AppHttpCodeEnum.GOODS_CATEGORY_ERROR_NOT_BLANK;
import static com.fg.pro.model.enums.AppHttpCodeEnum.GOODS_ERROR_NOT_BLANK;
import static com.fg.pro.trade.utils.GmRequestUrl.REDIS_LOCK_URL;

/**
 * 销售报表信息(TradeSale)表服务实现类
 *
 * @author makejava
 * @since 2025-08-28 10:00:40
 */
@Slf4j
@Service("tradeSaleService")
public class TradeSaleServiceImpl extends ServiceImpl<TradeSaleDao, TradeSale> implements TradeSaleService {
    @Resource
    private PoiUtils poiUtils;
    @Autowired
    RedissonClient redissonClient;
    @Resource
    private TradeSaleOtherService tradeSaleOtherService;
    @Resource
    private TradeGoodsService tradeGoodsService;

    @Resource
    private TradeCategoryService tradeCategoryService;
    @Resource
    private TradeCustomerService tradeCustomerService;
    @Override
    public PageInfo getPage(Integer pageNum, Integer pageSize, Date start, Date end, String goodsName) {
        SimpleDateFormat sdfs = new SimpleDateFormat("yyyy-MM-dd");
        String startStr = sdfs.format(cn.hutool.core.date.DateUtil.beginOfDay(start));
        String endStr = sdfs.format(DateUtil.endOfDay(end));
        System.out.println(startStr);
        System.out.println(endStr);
        PageHelper.startPage(pageNum, pageSize);
        List<TradeSale> saleList = query()
                .like(StrUtil.isNotBlank(goodsName), "sale_goods_name", goodsName)
                .ge("create_time", startStr).le("create_time", endStr).orderByDesc("create_time")
                .list();
        PageInfo<TradeSale> pageInfo = new PageInfo(saleList);
        return pageInfo;
    }

    @Override
    public Boolean upload(MultipartFile multipartFile, Date start, Date end) {
        RLock lock = redissonClient.getLock(REDIS_LOCK_URL+ "uploadSaleExcel");
        boolean tryLock = lock.tryLock();
        if(!tryLock){
            return false;
        }
        try {
            return uploadSaleExcel(multipartFile,start,end);
        } catch (RuntimeException | IOException | ParseException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    private Boolean uploadSaleExcel(MultipartFile multipartFile, Date start, Date end) throws IOException, ParseException {
        Workbook workbook = new XSSFWorkbook(multipartFile.getInputStream());
        // 1.1 准备好 商品，商品分类，客户数据
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat dfs = new SimpleDateFormat("yyyyMMdd");
        String dateStr = dateFormat.format(start);
        String dateEnd = dateFormat.format(end);
        Map<String, Long> goodsIdAndCode = tradeGoodsService.getIdAndCode();
        Map<String, Long> customerIdAndCode = tradeCustomerService.getIdAndCode();
        HashMap<String, Long> categoryIdAndName = tradeCategoryService.getIdAndName();

//        // 5.1 查当日的库存报表数据
//        List<TradeStock> stockList = tradeStockService.query().eq("create_time", dateStr).list();
//        if(stockList.isEmpty()){
//            throw new CustomException(UPLOAD_SALE_NULL_STOCK_ERROR);
//        }
        // 1 将excel转换成list数据
        Sheet sheetAt = workbook.getSheetAt(0);
        int lastRowNum = sheetAt.getLastRowNum();
        Row row = null;
        LinkedList<TradeSale> newSaleList = new LinkedList<>();
        LinkedList<TradeSaleOther> newSaleOtherList = new LinkedList<>();

        for (int i = 1; i <= lastRowNum - 1; i++) {
            row = sheetAt.getRow(i);
            TradeSale tradeSale = new TradeSale();
//   `id`bigint NOT NULL AUTO_INCREMENT COMMENT '主键',
            //  订单号
            if (row.getCell(0) != null) {
                row.getCell(0).setCellType(CellType.STRING);
                String orderCode = row.getCell(0).getStringCellValue().trim();
                tradeSale.setSaleGoodsOrderCode(orderCode);
            }
//  `create_time`datetime DEFAULT NULL COMMENT '下单日期',
            if (row.getCell(1) != null) {
                row.getCell(1).setCellType(CellType.STRING);
                String createTimeStr = row.getCell(1).getStringCellValue().trim();
                System.out.println(createTimeStr);
                Date createDate = dfs.parse(createTimeStr);
                tradeSale.setCreateTime(createDate);
            }
//  `customer_id`bigint DEFAULT NULL COMMENT '客户id',
//  `sale_customer_code`varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '客户编码', 2
            if (row.getCell(2) != null) {
                String customerCode = row.getCell(2).getStringCellValue().trim();
                Long customerId = customerIdAndCode.get(customerCode);
                tradeSale.setSaleCustomerCode(customerCode);
                tradeSale.setCustomerId(customerId);
            }
//  `sale_customer_name`varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '客户名称',
            if (row.getCell(3) != null) {
                String customerName = row.getCell(3).getStringCellValue().trim();
                tradeSale.setSaleCustomerName(customerName);
            }
//  `sale_customer_tag`varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '客户标签', 4
            if (row.getCell(4) != null) {
                String customerTag = row.getCell(4).getStringCellValue().trim();
                tradeSale.setSaleCustomerTag(customerTag);
            }
//  `sale_customer_line`varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '客户线路', 5
            if (row.getCell(5) != null) {
                String customerLine = row.getCell(5).getStringCellValue().trim();
                tradeSale.setSaleCustomerLine(customerLine);
            }
//  `goods_id`bigint DEFAULT NULL COMMENT '商品id',
//  `sale_goods_code`varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '商品编码', 7
            if (row.getCell(7) != null) {
                String goodsCode = row.getCell(7).getStringCellValue().trim();
                Long goodsId = goodsIdAndCode.get(goodsCode);
                if (goodsId == null) {
                    log.info("----------------------------------------------" + goodsCode);
                    log.info(String.valueOf(i));
                    throw new CustomException(GOODS_ERROR_NOT_BLANK);
                }
                tradeSale.setGoodsId(goodsId);
                tradeSale.setSaleGoodsCode(goodsCode);
            }
//  `sale_goods_name`varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '商品名称', 8
            if (row.getCell(8) != null) {
                String goodsName = row.getCell(8).getStringCellValue().trim();
                tradeSale.setSaleGoodsName(goodsName);
            }
            //8 商品描述 不要
//  `sale_goods_tax_code`varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '商品税收分类编码', 9
            if (row.getCell(10) != null) {
                String goodsType = row.getCell(10).getStringCellValue().trim();
                tradeSale.setSaleGoodsTaxCode(goodsType);
            }
//  `sale_goods_tag`varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '商品标签', 11
            if (row.getCell(11) != null) {
                String goodsTag = row.getCell(11).getStringCellValue().trim();
                tradeSale.setSaleGoodsTag(goodsTag);
            }
//  `sale_category_fir_id`bigint DEFAULT NULL COMMENT '商品一级分类id',
//  `sale_category_fir_name`varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '商品一级分类名称', 12
            if (row.getCell(12) != null) {
                String categoryName = row.getCell(12).getStringCellValue().trim();
                Long categoryId = categoryIdAndName.get(categoryName);
                if (categoryId == null) {
                    throw new CustomException(GOODS_CATEGORY_ERROR_NOT_BLANK);
                }
                tradeSale.setSaleCategoryFirId(categoryId);
                tradeSale.setSaleCategoryFirName(categoryName);
            }

//  `sale_category_sec_id`bigint DEFAULT NULL COMMENT '商品二级分类id',
//  `sale_category_sec_name`varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '商品二级分类名称', 13
            if (row.getCell(13) != null) {
                String categoryName = row.getCell(13).getStringCellValue().trim();
                if (StrUtil.isNotBlank(categoryName)) {
                    Long categoryId = categoryIdAndName.get(categoryName);
                    if (categoryId == null) {
                        throw new CustomException(GOODS_CATEGORY_ERROR_NOT_BLANK);
                    }
                    tradeSale.setSaleCategorySecId(categoryId);
                    tradeSale.setSaleCategorySecName(categoryName);
                }
            }
//  `sale_goods_base_unit`varchar(50) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '基本单位',14
            if (row.getCell(14) != null) {
                String str = row.getCell(14).getStringCellValue().trim();
                tradeSale.setSaleGoodsBaseUnit(str);
            }
//  `sale_goods_base_price`decimal(10, 2) DEFAULT NULL COMMENT '单价（基本单位）', 15
            row.getCell(15).setCellType(CellType.STRING);
            if (row.getCell(15) != null) {
                String str = row.getCell(15).getStringCellValue().trim();
                tradeSale.setSaleGoodsBasePrice(Double.valueOf(str));
            }
//  `sale_goods_base_outstock`decimal(10, 2) DEFAULT NULL COMMENT '出库数（基本单位）', 16
            row.getCell(16).setCellType(CellType.STRING);
            if (row.getCell(16) != null) {
                String str = row.getCell(16).getStringCellValue().trim();
                tradeSale.setSaleGoodsBaseOutstock(Double.valueOf(str));
            }
//  `sale_goods_order_outstock`decimal(10, 2) DEFAULT NULL COMMENT '出库数（下单单位）', 17
            row.getCell(17).setCellType(CellType.STRING);
            if (row.getCell(17) != null) {
                String str = row.getCell(17).getStringCellValue().trim();
                tradeSale.setSaleGoodsOrderOutstock(Double.valueOf(str));
            }
//  `sale_goods_order_unit`varchar(50) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '下单单位	', 18
            if (row.getCell(18) != null) {
                String str = row.getCell(18).getStringCellValue().trim();
                tradeSale.setSaleGoodsOrderUnit(str);
            }
//  `sale_goods_order_quantity`decimal(10, 2) DEFAULT NULL COMMENT '下单数', 19
            row.getCell(19).setCellType(CellType.STRING);
            if (row.getCell(19) != null) {
                String str = row.getCell(19).getStringCellValue().trim();
                tradeSale.setSaleGoodsOrderQuantity(tradeSale.getSaleGoodsBaseOutstock());
            }
//  `sale_goods_order_unit_price`decimal(10, 2) DEFAULT NULL COMMENT '单价（下单单位', 20
            row.getCell(20).setCellType(CellType.STRING);
            if (row.getCell(20) != null) {
                String str = row.getCell(20).getStringCellValue().trim();
                tradeSale.setSaleGoodsOrderUnitPrice(Double.valueOf(str));
            }
//  `sale_goods_order_price`decimal(10, 2) DEFAULT NULL COMMENT '下单金额', 21
            row.getCell(21).setCellType(CellType.STRING);
            if (row.getCell(21) != null) {
                String str = row.getCell(21).getStringCellValue().trim();
                tradeSale.setSaleGoodsOrderPrice(Double.valueOf(str));
            }
//  `sale_goods_sale_outstock_price`decimal(10, 2) DEFAULT NULL COMMENT '销售出库金额', 55
            row.getCell(22).setCellType(CellType.STRING);
            if (row.getCell(22) != null) {
                String str = row.getCell(22).getStringCellValue().trim();
                tradeSale.setSaleGoodsSaleOutstockPrice(Double.valueOf(str));
            }
//  `sale_goods_sale_return_price`decimal(10, 2) DEFAULT NULL COMMENT '售后金额', 23
            row.getCell(23).setCellType(CellType.STRING);
            if (row.getCell(23) != null) {
                String str = row.getCell(23).getStringCellValue().trim();
                tradeSale.setSaleGoodsSaleReturnPrice(Double.valueOf(str));
            }
//  `sale_goods_real_deal_price`decimal(10, 2) DEFAULT NULL COMMENT '实际成交额', 24
            row.getCell(24).setCellType(CellType.STRING);
            if (row.getCell(24) != null) {
                String str = row.getCell(24).getStringCellValue().trim();
                tradeSale.setSaleGoodsRealDealPrice(Double.valueOf(str));
            }
//  `sale_goods_sale_tax_price`decimal(10, 2) DEFAULT NULL COMMENT '销售税额', 25
            row.getCell(25).setCellType(CellType.STRING);
            if (row.getCell(25) != null) {
                String str = row.getCell(25).getStringCellValue().trim();
                tradeSale.setSaleGoodsSaleTaxPrice(Double.valueOf(str));
            }
            //todo 先用库存成本均价计算
//  `sale_goods_outstock_cost_price`decimal(10, 2) DEFAULT NULL COMMENT '出库成本金额', 26
            row.getCell(26).setCellType(CellType.STRING);
            if (row.getCell(26) != null) {
                String str = row.getCell(26).getStringCellValue().trim();
                tradeSale.setSaleGoodsOutstockCostPrice(Double.valueOf(str));
            }
//            List<TradeStock> collect = stockList.stream().filter(item -> {
////                return item.getGoodsId() == tradeSale.getGoodsId();
//                return NumberUtil.compare(item.getGoodsId(),tradeSale.getGoodsId())==0;
//            }).collect(Collectors.toList());
//            if(collect.size()!=1){
//                log.info("----------------------------------------------库存货值表出现问题");
//                log.info("----------------------------------------------"+tradeSale.getGoodsId());
//                log.info("----------------------------------------------"+tradeSale.getSaleGoodsName());
//                log.info("----------------------------------------------"+collect.toString());
////                throw new CustomException(UPLOAD_SALE_GOODS_ERROR);
//                continue;
//            }
//            sale_goods_order_quantity
//            tradeSale.setSaleGoodsOutstockCostPrice(NumberUtil.mul(collect.get(0).getStockEndAvePrice(),tradeSale.getSaleGoodsOrderQuantity()));
//            Double result = tradeStockService.getEndAvePriceByLast(tradeSale.getGoodsId(), date);
//            Double result = tradeStockSheetDetailService.getAvgPrice(tradeSale.getGoodsId(), date);
//            if (result == null || result ==0) {
////                row.getCell(23).setCellType(CellType.STRING);
////                if (row.getCell(23) != null) {
////                    String str = row.getCell(23).getStringCellValue().trim();
////                    tradeSale.setSaleGoodsOutstockCostPrice(Double.valueOf(str));
////                }
//                System.out.println(tradeSale.getGoodsId());
//                continue;
//            } else {
//                tradeSale.setSaleGoodsOutstockCostPrice(NumberUtil.mul(result, tradeSale.getSaleGoodsOrderQuantity()));
//            }

            //  `sale_goods_sale_gross_price`decimal(10, 2) DEFAULT NULL COMMENT '销售毛利', 27
            row.getCell(27).setCellType(CellType.STRING);
            if (row.getCell(27) != null) {
                String str = row.getCell(27).getStringCellValue().trim();
                tradeSale.setSaleGoodsSaleGrossPrice(Double.valueOf(str));
            }
//  `sale_goods_sale_gorss_margin`decimal(10, 2) DEFAULT NULL COMMENT '销售毛利率 税率 *100', 28
            Cell cell25 = row.getCell(28);
//            cell25.setCellType(CellType.STRING);
            if (cell25 != null) {
                if (cell25.getCellType() != CellType.STRING) {
                    tradeSale.setSaleGoodsSaleGrossMargin((cell25.getNumericCellValue()));
                } else {
                    String ceilStr = cell25.getStringCellValue().trim();
                    String str = ceilStr.split("%")[0];
                    tradeSale.setSaleGoodsSaleGrossMargin(Double.valueOf(str));
                }

            }
//  `sale_goods_outstock_differ_price`decimal(10, 2) DEFAULT NULL COMMENT '出库金额补差', 29
            Cell cell26 = row.getCell(29);
            cell26.setCellType(CellType.STRING);
            if (cell26 != null) {
                String str = cell26.getStringCellValue().trim();
                tradeSale.setSaleGoodsOutstockDifferPrice(Double.valueOf(str));
            }
//  `sale_goods_order_differ_price`decimal(10, 2) DEFAULT NULL COMMENT '下单金额补差', 30
            Cell cell27 = row.getCell(30);
            cell27.setCellType(CellType.STRING);
            if (cell27 != null) {
                String str = cell27.getStringCellValue().trim();
                tradeSale.setSaleGoodsOrderDifferPrice(Double.valueOf(str));
            }
//  `sale_goods_order_gross_margin`decimal(10, 2) DEFAULT NULL COMMENT '成本毛利率 税率 *100', 31
//            row.getCell(28).setCellType(CellType.STRING);
            Cell cell28 = row.getCell(31);
            if (cell28.getCellType() != null) {
                if (cell28.getCellType() != CellType.STRING) {
                    tradeSale.setSaleGoodsOrderGrossMargin((cell28.getNumericCellValue()));
                } else {
                    String ceilStr = cell28.getStringCellValue().trim();
                    String str = ceilStr.split("%")[0];
                    tradeSale.setSaleGoodsOrderGrossMargin(Double.valueOf(str));
                }
            }
            //todo 先用库存成本均价
//  `sale_goods_outstock_cost_avg_price`decimal(10, 2) DEFAULT NULL COMMENT '出库成本均价', 32
            row.getCell(32).setCellType(CellType.STRING);
            if (row.getCell(32) != null) {
                String str = row.getCell(32).getStringCellValue().trim();
                tradeSale.setSaleGoodsOutstockCostAvgPrice(Double.valueOf(str));
            }

//            tradeSale.setSaleGoodsOutstockCostAvgPrice(collect.get(0).getStockEndAvePrice());
//            if (result == null || result==0) {
////                row.getCell(29).setCellType(CellType.STRING);
////                if (row.getCell(29) != null) {
////                    String str = row.getCell(29).getStringCellValue().trim();
////                    tradeSale.setSaleGoodsOutstockCostAvgPrice(Double.valueOf(str));
////                }
//                System.out.println(tradeSale.getGoodsId());
//                continue;
//            } else {
//                tradeSale.setSaleGoodsOutstockCostAvgPrice(result);
//            }

//  `sale_goods_tax_margin`decimal(10, 2) DEFAULT NULL COMMENT '税率 *100', 33
//            row.getCell(30).setCellType(CellType.STRING);
            if (row.getCell(33) != null) {
                Cell cell = row.getCell(33);
                String str = row.getCell(33).getStringCellValue().trim().split("%")[0];
                tradeSale.setSaleGoodsTaxMargin(Double.valueOf(str));
            }

            //售后成本
            row.getCell(34).setCellType(CellType.STRING);
            if (row.getCell(34) != null) {
                String str = row.getCell(34).getStringCellValue().trim();
                tradeSale.setSaleGoodsSaleReturnCostPrice(Double.valueOf(str));
            }

            if (tradeSale.getSaleGoodsRealDealPrice()>0 && tradeSale.getSaleGoodsSaleReturnCostPrice()>0) {
                //出库成本重新计算
                Double outStockCostPrice = NumberUtil.sub(tradeSale.getSaleGoodsOutstockCostPrice() , tradeSale.getSaleGoodsSaleReturnCostPrice());
                tradeSale.setSaleGoodsOutstockCostPrice(outStockCostPrice);
                //出库数重新计算
                Double baseOutStock = NumberUtil.div(outStockCostPrice , tradeSale.getSaleGoodsOutstockCostAvgPrice());
                tradeSale.setSaleGoodsBaseOutstock(baseOutStock);
            }
            if(tradeSale.getSaleGoodsSaleReturnPrice()==0){
                newSaleList.add(tradeSale);
            }else {
                TradeSaleOther tradeSaleOther = BeanUtil.copyProperties(tradeSale, TradeSaleOther.class);
                newSaleOtherList.add(tradeSaleOther);
            }

        }
        // 2.1 删除当日旧数据
        QueryWrapper<TradeSale> queryWrapper = new QueryWrapper<TradeSale>().ge("create_time", dateStr).le("create_time",dateEnd);
        boolean remove = remove(queryWrapper);
        QueryWrapper<TradeSaleOther> queryOtherWrapper = new QueryWrapper<TradeSaleOther>().ge("create_time", dateStr).le("create_time",dateEnd);
        boolean removes = tradeSaleOtherService.remove(queryOtherWrapper);
        // 2.2 添加当日新数据
        boolean saveBatch = saveBatch(newSaleList);
        boolean saveOtherBatch = tradeSaleOtherService.saveBatch(newSaleOtherList);
        return saveBatch;
    }
}

